import os
import sys
import subprocess
import webbrowser
import time

def main():
    """启动财务数据可视化分析系统"""
    print("正在启动财务数据可视化分析系统...")
    
    # 获取项目根目录
    root_dir = os.path.dirname(os.path.abspath(__file__))
    app_path = os.path.join(root_dir, "app", "app.py")
    
    # 检查app.py是否存在
    if not os.path.exists(app_path):
        print(f"错误: 找不到应用入口文件 {app_path}")
        return
    
    # 检查是否已安装依赖
    try:
        import streamlit
        import akshare
        import pandas
        import plotly
    except ImportError as e:
        print(f"错误: 缺少必要的依赖库 - {e}")
        install = input("是否要安装所需依赖? (y/n): ")
        if install.lower() == 'y':
            print("正在安装依赖...")
            requirements_path = os.path.join(root_dir, "requirements.txt")
            subprocess.call([sys.executable, "-m", "pip", "install", "-r", requirements_path])
            print("依赖安装完成")
        else:
            print("请先安装依赖后再运行程序")
            return
    
    # 创建必要的目录
    os.makedirs(os.path.join(root_dir, "data", "raw"), exist_ok=True)
    os.makedirs(os.path.join(root_dir, "data", "processed"), exist_ok=True)
    
    # 启动Streamlit应用
    print("正在启动应用服务器...")
    process = subprocess.Popen(
        [sys.executable, "-m", "streamlit", "run", app_path, "--server.headless", "true"],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True
    )
    
    # 等待服务器启动
    time.sleep(3)
    
    # 打开浏览器
    print("正在打开浏览器...")
    webbrowser.open("http://localhost:8501")
    
    print("\n财务数据可视化分析系统已启动!")
    print("请在浏览器中使用应用，按Ctrl+C退出程序")
    
    try:
        # 保持程序运行，直到用户按Ctrl+C
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\n正在关闭应用...")
        process.terminate()
        print("应用已关闭")

if __name__ == "__main__":
    main()